package xt.outfood.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import xt.outfood.common.Result;
import xt.outfood.entity.Employee;
import xt.outfood.service.EmployeeService;

/**
 * Spring Cache缓存测试
 *
 * @author xiaozhua
 * @date 2022/9/2 13:53
 */

@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private CacheManager cacheManager;

    /**
     * @param id
     * @return
     * @Cacheable(cacheNames,key="#id")先从缓存中读取，如果缓存中没有数据，再从数据库中读取
     * 存的是查询到的这一条数据，或者这些数据,名字随便取
     * 当要调用改方法时，程序会先去缓存中看有没有数据，有的话就不执行这个数据
     * condition为条件
     */
//    @Cacheable(cacheNames = "Employee", key = "#id")
    @Cacheable(value = "employee",key = "#id",condition = "#result!=null")
    @GetMapping("/{id}")
    public Result<Employee> getById(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        return Result.success(employee);
    }

    /**
     * @CachePut修改数据库的数据，同时更新缓存
     * @param employee
     * @return
     */
    @CachePut(cacheNames = "Employee",key = "#result.id")
    @PutMapping
    public Result<String> update(@RequestBody Employee employee) {
         employeeService.updateById(employee);
        return Result.success("修改成功");
    }

    /**
     * @CacheEvict删除数据，同时删除缓存
     * @param id
     * @return
     */
    @CacheEvict(cacheNames = "employee",key="#id")
    @DeleteMapping("/{id}")
    public boolean delEmployee(@PathVariable Long id){
        return employeeService.removeById(id);
    }
}
